<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>值班表编辑 - {{ room_number }}号监室</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='lib/flatpickr/flatpickr.min.css') }}">
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            max-height: calc(100vh - 80px);
            overflow-y: auto;
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 25px;
            font-size: 22px;
            font-weight: 500;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        .form-group {
            margin-bottom: 16px;
        }
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #444;
            font-size: 14px;
            letter-spacing: 0.3px;
        }
        .form-control {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
            font-size: 14px;
        }
        .person-select {
            height: 38px;
            padding: 6px 12px;
        }
        textarea.form-control {
            min-height: 120px;
            resize: vertical;
        }
        .shift-group {
            margin-bottom: 15px;
            padding: 15px;
            border: 1px solid #e8e8e8;
            border-radius: 6px;
            background-color: white;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
        }
        .shift-group:last-child {
            margin-bottom: 0;
        }
        .shift-title {
            font-size: 16px;
            margin-bottom: 15px;
            color: #333;
            font-weight: 500;
            display: flex;
            align-items: center;
            padding-bottom: 10px;
            border-bottom: 1px solid #f0f0f0;
        }
        .shift-title:before {
            content: "";
            display: inline-block;
            width: 4px;
            height: 16px;
            background-color: #1890ff;
            margin-right: 10px;
            border-radius: 2px;
        }
        .person-select-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
        }
        .person-select-wrapper {
            display: flex;
            flex-direction: column;
        }
        .person-select-wrapper label {
            font-size: 13px;
            color: #666;
            margin-bottom: 4px;
        }
        .actions {
            text-align: right;
            margin-top: 25px;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }
        .btn {
            padding: 8px 18px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
            border: 1px solid transparent;
        }
        .btn-save {
            background-color: #1890ff;
            color: white;
            margin-left: 10px;
            transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
            will-change: transform, box-shadow;
        }
        .btn-save:hover {
            background-color: #40a9ff;
            transform: translateY(-1px);
            box-shadow: 0 2px 6px rgba(24, 144, 255, 0.3);
        }
        .btn-save:active {
            transform: translateY(0);
            box-shadow: none;
        }
        .btn-cancel {
            background-color: white;
            color: #666;
            border-color: #d9d9d9;
            transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
            will-change: transform, box-shadow;
        }
        .btn-cancel:hover {
            color: #1890ff;
            border-color: #1890ff;
            transform: translateY(-1px);
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
        }
        .btn-cancel:active {
            transform: translateY(0);
            box-shadow: none;
        }
        .required {
            color: red;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>{{ room_number }}号监室 - 值班表编辑</h1>
        <form id="scheduleForm">
            <div class="form-group">
                <label class="form-label">选择日期</label>
                <input type="text" id="dateSelect" class="form-control"
                       placeholder="选择日期" readonly>
            </div>

            {% for shift in ['午班', '夜班1', '夜班2', '夜班3'] %}
            <div class="shift-group">
                <div class="shift-title">{{ shift }}</div>
                <div class="form-group">
                    <label class="form-label">值班人员1</label>
                    <select class="form-control person-select" data-shift="{{ shift }}" data-position="1">
                        <option value="">-- 请选择 --</option>
                        {% for person in persons %}
                        <option value="{{ person.id }}" 
                            {% if shifts[shift][0].id == person.id %}selected{% endif %}>
                            {{ person.name }}
                        </option>
                        {% endfor %}
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">值班人员2</label>
                    <select class="form-control person-select" data-shift="{{ shift }}" data-position="2">
                        <option value="">-- 请选择 --</option>
                        {% for person in persons %}
                        <option value="{{ person.id }}" 
                            {% if shifts[shift][1].id == person.id %}selected{% endif %}>
                            {{ person.name }}
                        </option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            {% endfor %}

            <div class="form-group">
                <label class="form-label">调整理由 <span class="required">*</span></label>
                <textarea id="reason" class="form-control" rows="3"
                          placeholder="请输入调整理由" required></textarea>
            </div>

            <div class="actions">
                <button type="submit" class="btn btn-save">保存</button>
                <button type="button" class="btn btn-cancel">取消</button>
            </div>
        </form>
    </div>

    <script src="{{ url_for('static', filename='lib/flatpickr/flatpickr.js') }}"></script>
    <script src="{{ url_for('static', filename='lib/flatpickr/zh.js') }}"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化日期选择器
            const today = new Date('{{ today }}');
            const minDate = new Date('{{ week_dates[0].strftime('%Y-%m-%d') }}');
            const maxDate = new Date('{{ week_dates[-1].strftime('%Y-%m-%d') }}');

            const datePicker = flatpickr('#dateSelect', {
                locale: 'zh',
                defaultDate: today,
                minDate: minDate,
                maxDate: maxDate,
                disable: [
                    function(date) {
                        // 禁用今天之前的日期
                        return date < today;
                    }
                ],
                onChange: function(selectedDates, dateStr) {
                    document.getElementById('dateSelect').value = dateStr;
                    // 刷新班次人员
                    refreshShiftPersonnel(dateStr);
                }
            });
            // 设置初始值
            document.getElementById('dateSelect').value = today.toISOString().split('T')[0];

            // 表单验证
            const form = document.getElementById('scheduleForm');
            form.addEventListener('submit', function(e) {
                e.preventDefault();

                // 验证调整理由
                const reason = document.getElementById('reason').value.trim();
                if (!reason) {
                    alert('请填写调整理由');
                    return;
                }

                // 获取日期值
                const selectedDate = document.getElementById('dateSelect').value;
                if (!selectedDate) {
                    alert('请选择日期');
                    return;
                }

                // 使用后端提供的原始班次数据
                const originalShifts = JSON.parse('{{ original_shifts|tojson|safe }}');
                
                // 初始化select元素的原始值属性
                document.querySelectorAll('.person-select').forEach(select => {
                    const shiftName = select.dataset.shift;
                    const position = select.dataset.position;
                    
                    // 从后端数据获取原始值
                    const originalShift = originalShifts[shiftName] || [];
                    const originalPerson = originalShift[position-1] || {};
                    
                    // 设置select元素的原始值属性
                    select.dataset.originalValue = originalPerson.id || '';
                    select.dataset.originalText = originalPerson.name || '';
                });

                // 收集表单数据
                const formData = {
                    date: selectedDate,
                    shifts: {},
                    original_shifts: originalShifts,
                    reason: reason
                };

                // 收集新班次数据
                const personSelects = document.querySelectorAll('.person-select');
                personSelects.forEach(select => {
                    const shiftName = select.dataset.shift;
                    const position = select.dataset.position;
                    
                    if (!formData.shifts[shiftName]) {
                        formData.shifts[shiftName] = [];
                    }
                    
                    if (select.value) {
                        formData.shifts[shiftName][position-1] = {
                            id: select.value,
                            name: select.options[select.selectedIndex].text
                        };
                    }
                });

                // 验证每个班次是否都有两个人
                for (const shift in formData.shifts) {
                    if (formData.shifts[shift].length !== 2 || !formData.shifts[shift][0] || !formData.shifts[shift][1]) {
                        alert(`请为${shift}选择两名值班人员`);
                        return;
                    }
                }

                // 发送数据到服务器
                fetch(`/save_schedule_edit/{{ room_number }}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        room_number: '{{ room_number }}',
                        user_id: '{{ session.user_id }}',
                        operation_time: new Date().toISOString(),
                        change_reason: formData.reason,
                        date: formData.date,
                        shifts: formData.shifts,
                        original_shifts: formData.original_shifts
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('值班表修改已保存');
                        window.location.href = '/room/{{ room_number }}';
                    } else {
                        alert(data.message || '保存失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('保存过程中发生错误');
                });
            });

            // 取消按钮事件
            document.querySelector('.btn-cancel').addEventListener('click', function() {
                if (confirm('确定要取消编辑吗？所有更改将不会保存。')) {
                    window.location.href = '/room/{{ room_number }}';
                }
            });

            // 刷新班次人员函数
            function refreshShiftPersonnel(dateStr) {
                fetch(`/get_schedule_by_date/{{ room_number }}?date=${dateStr}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // 更新下拉选择框
                            updateShiftSelects(data.shifts);
                        } else {
                            alert('获取班次数据失败: ' + data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('获取班次数据时发生错误');
                    });
            }

            // 更新班次选择框
            function updateShiftSelects(shifts) {
                // 清空所有选择框
                document.querySelectorAll('.person-select').forEach(select => {
                    select.selectedIndex = 0; // 重置为第一个选项（-- 请选择 --）
                });

                // 根据返回的数据设置选择框的值
                for (const shiftName in shifts) {
                    if (shifts.hasOwnProperty(shiftName)) {
                        const shift = shifts[shiftName];
                        
                        // 更新第一个人
                        if (shift[0] && shift[0].id) {
                            const select1 = document.querySelector(`.person-select[data-shift="${shiftName}"][data-position="1"]`);
                            if (select1) {
                                select1.value = shift[0].id;
                            }
                        }
                        
                        // 更新第二个人
                        if (shift[1] && shift[1].id) {
                            const select2 = document.querySelector(`.person-select[data-shift="${shiftName}"][data-position="2"]`);
                            if (select2) {
                                select2.value = shift[1].id;
                            }
                        }
                    }
                }
            }
        });
    </script>
</body>
</html>
